﻿var PrimesCalculator = WinJS.Class.define(function () {
    this._workersCount = 0;
    this._calculatePrimesRangeWorker = new Worker("/js/workers/calculate-primes-range-worker.js");
    this._calculateFirstNPrimesWorker = new Worker("/js/workers/calculate-first-N-primes-worker.js");
    this._calculateFrom0ToNPrimesWorker = new Worker("/js/workers/calculate-primes-from-0-to-N-worker.js");
}, {
    calculatePrimesRange: function (fromNumber, toNumber) {
        var self = this;
        return new WinJS.Promise(function (complete, error) {
            self._workersCount++;
            if (self._workersCount < 3) {
                self._calculatePrimesRangeWorker.onmessage = function (event) {
                    self._workersCount--;
                    var workerResult = event.data;
                    complete(workerResult);
                }

                self._calculatePrimesRangeWorker.postMessage({
                    firstNumber: fromNumber,
                    secondNumber: toNumber
                });
            } else {
                error("You can make max 3 calculations at once.");
            }
        });
    },

    calculateFirstNPrimes: function (firstNPrimes) {
        var self = this;
        return new WinJS.Promise(function (complete, error) {
            self._workersCount++;
            if (self._workersCount < 3) {
                self._calculateFirstNPrimesWorker.onmessage = function (event) {
                    self._workersCount--;
                    var workerResult = event.data;
                    complete(workerResult);
                }

                self._calculateFirstNPrimesWorker.postMessage({
                    firstNPrimes: firstNPrimes
                });
            } else {
                error("You can make max 3 calculations at once.");
            }
        });
    },

    calculateToNPrimes: function (toNumber) {
        var self = this;
        return new WinJS.Promise(function (complete, error) {
            self._workersCount++;
            if (self._workersCount < 3) {
                self._calculateFrom0ToNPrimesWorker.onmessage = function (event) {
                    self._workersCount--;
                    var workerResult = event.data;
                    complete(workerResult);
                }

                self._calculateFrom0ToNPrimesWorker.postMessage({
                    toNumber: toNumber
                });
            } else {
                error("You can make max 3 calculations at once.");
            }
        });
    }
}, {});
